package gweb

import (
	"encoding/json"
	"time"

	"gitee.com/makitdone/gweb/v2/conf"
	"github.com/golang-jwt/jwt/v4"
	"github.com/gookit/goutil/timex"
)

type Claim struct {
	jwt.RegisteredClaims
	IsSuperuser bool
	UserClaim   any
}

func (c *Claim) Bind(dest any) error {
	bytes, _ := json.Marshal(c.UserClaim)
	return json.Unmarshal(bytes, dest)
}

type JWT struct {
	*conf.JwtConfig
}

func (j *JWT) MakeToken(payload any, isSuperuser bool) (string, error) {
	ep, _ := timex.ToDuration(j.ExpiresTime)
	claim := Claim{
		IsSuperuser: isSuperuser,
		UserClaim:   payload,
		RegisteredClaims: jwt.RegisteredClaims{
			Audience:  jwt.ClaimStrings{"GVA"},                   // 受众
			NotBefore: jwt.NewNumericDate(time.Now().Add(-1000)), // 签名生效时间
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(ep)),    // 过期时间 7天  配置文件
			Issuer:    j.Issuer,                                  // 签名的发行者
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	return token.SignedString([]byte(j.SigningKey))
}

func (j *JWT) ParseToken(token string) (*Claim, error) {
	var claim Claim
	if _, err := jwt.ParseWithClaims(token, &claim, func(token *jwt.Token) (i interface{}, err error) {
		return []byte(j.SigningKey), nil
	}); err != nil {
		return nil, err
	}
	return &claim, nil
}
